#!/usr/bin/env python
# encoding=utf-8
from flask import *
from flask.ext.login import login_required, current_user
from xtls.timeparser import now
from xtls.util import sha1
import json

from . import web
from .. import dao, logger
from ..models import UserLog
from ..util import convert


def build_id(*args):
    return sha1('#'.join(unicode(x) for x in args))


def calc_page_bar(page, max_page=None):
    if page == 1:
        pages = [1, 2, 1, 1, 2, 3, 4, 5]
    elif page == 2:
        pages = [1, 3, 2, 1, 2, 3, 4, 5]
    else:
        pages = [page - 1, page + 1, page] + range(page - 2, page + 3)
    if isinstance(max_page, int):
        if max_page < pages[1]:
            pages[1] = max_page
        pages = pages[:3] + [x for x in pages[3:] if x <= max_page]
    return pages


@web.route('/index')
@web.route('/')
@web.route('/<int:page>')
@login_required
def index(page=1):
    if page > 10:
        flash(u'目前仅可以直接查看前10页数据。')
        return redirect('/')
    logger.log(UserLog(logger.VIEW_PAGE_EVENT, '%s' % page))
    data = dao.select_db(page=page)
    param = {
        'title': u'首页',
        'data': data,
        'pages': calc_page_bar(page)
    }
    return render_template('index.html', **param)


@web.route('/detail/<sid>')
@login_required
def detail(sid):
    data = dao.render_anno_db(dao.select_db_single('stockAnnouncement', {'_id': sid}))
    collected = dao.select_db_single(
        'collect',
        {'_id': build_id(current_user.uuid, sid, 'stockAnnouncement')},
        db='lawyer_asst'
    )
    file_meta = dao.select_db_single('fileMetaData', {'key': data['file']}, db='qiniu')
    if not file_meta:
        # todo 替换下面两行
        # return Response('Server error.', 500)
        file_meta = {}
    filesize = float(file_meta.get('filesize', 0))
    if filesize <= (1 << 20):
        filesize = '%dKB' % int((filesize + 512) / 1024)
    else:
        filesize = '%.2fMB' % (filesize / 1024 / 1024)
    data['filesize'] = filesize
    param = {
        'data': data,
        'collected': collected,
        'title': u'(%s-%s) %s' % (data['companyShortName'], data['stockCode'], data['title']),
    }
    logger.log(UserLog(logger.VIEW_DETAIL_EVENT, sid))
    return render_template('detail.html', **param)


@web.route('/about')
def about():
    return render_template('about.html', title=u'关于')


@web.route('/search', methods=['POST'])
@web.route('/search/<key>')
@web.route('/search/<key>/<int:page>')
def search(key='', page=1):
    if request.method == 'POST':
        keyword = request.form.get('keyword')
        before = request.form.get('before')
        querytype = request.form.get('querytype')
        if querytype == 'byresult' and before:
            keyword = before + '@`@' + keyword
        logger.log(UserLog(logger.SEARCH_EVENT, keyword))
        if not keyword:
            flash(u'您没有输入任何搜索条件')
            return redirect('/')
        return redirect('/search/%s' % keyword)

    if page > 10:
        flash(u'目前仅可以直接查看前10页数据。')
        return redirect(u'/search/' + key)

    keys = [x.strip() for x in key.split('@`@') if x.strip()]

    total, data = dao.select_es(keys, page)
    logger.log(UserLog(logger.VIEW_SEARCH_EVENT, u'%s/%s' % (key, page)))
    param = {
        'title': u'>'.join(keys),
        'data': data,
        'pages': calc_page_bar(page, max_page=(total + 9) / 10),
        'keyword': key,
        'showkeyword': u'>'.join(keys),
        'submit': u'在结果中搜索'
    }
    flash(u'您目前搜索条件为：%s，共搜索到%s条记录。' % (u'>'.join(keys), total))
    return render_template('search.html', **param)


@web.route('/highsearch', methods=['GET', 'POST'])
@web.route('/highsearch/<key>')
@web.route('/highsearch/<key>/<int:page>')
def high_search(key='', page=1):
    if request.method == 'POST':
        param = {'t-a': '', 't-o': '', 't-n': '', 'c-a': '', 'c-o': '', 'c-n': ''}
        for key in param:
            param[key] = filter(None, request.form.get(key, '').split(' '))
        return redirect(u'/highsearch/%s' % json.dumps(param, ensure_ascii=False).replace(' ', ''))

    if page > 10:
        flash(u'目前仅可以直接查看前10页数据。')
        return redirect(u'/highsearch/' + key)

    param = json.loads(key)

    total, data = dao.select_es_high(param)
    rst_param = {
        'title': u'搜索结果',
        'data': data,
        'pages': calc_page_bar(page, max_page=(total + 9) / 10),
        'keyword': key,
        'parsed': param,
        'reverse': True
    }
    flash(u'根据您目前的搜索条件，共搜索到%s条记录。' % total)
    return render_template('highsearch.html', **rst_param)


@web.route('/collect/<sid>', methods=['POST'])
@login_required
def collect(sid):
    if request.json['method'] == 'collect':
        logger.log(UserLog(logger.COLLECT_EVENT, 'collect<%s>' % sid))
        dao.insert_into_mongo(
            'lawyer_asst',
            'collect',
            {
                '_id': build_id(current_user.uuid, sid, 'stockAnnouncement'),
                'userUuid': current_user.uuid,
                'docId': sid,
                'docAt': 'stockAnnouncement',
                'collectTime': now()
            },
        )
    elif request.json['method'] == 'no-collect':
        logger.log(UserLog(logger.NO_COLLECT_EVENT, 'collect<%s>' % sid))
        dao.remove_from_db(
            'lawyer_asst', 'collect',
            {
                '_id': build_id(current_user.uuid, sid, 'stockAnnouncement')
            }
        )
    return ''


@web.route('/my-collect')
@web.route('/my-collect/<int:page>')
def my_collect(page=1):
    total, data = dao.select_collect(current_user.uuid, page)
    if not data:
        docs = []
    else:
        sids = [x['docId'] for x in data]
        docs = dao.select_db({'_id': {'$in': sids}})
    data = {
        'collectedDocs': docs,
        'pages': calc_page_bar(page, max_page=(total + 9) / 10),
    }
    return render_template('collect.html', title=current_user.username, **data)


@web.route('/me')
@login_required
def me():
    data = {}
    return render_template('me.html', title=current_user.username, **data)


@web.route('/me/trans', methods=['POST'])
@login_required
def trans():
    filemeta = request.files['pdffile']
    text = convert(filemeta.stream)
    filename = filemeta.filename

    return render_template('trans.html', title=filename, data=text, filename=filename)


@web.errorhandler(404)
def page_not_found(e):
    return render_template('404.html'), 404
